(function() {

  class AdminDashboard {
    constructor() {
        console.log("AdminDashboard 实例化");
        this.ws = null;
        this.initEventListeners();
        //this.fetchInitialData();
        //this.startStatusPolling();  //憋轮询了先，烦的要死
    }

    // 连接控制方法
    async controlConnection(action) {
        // try {
        //     console.log("不会这里都没吧");
        //     const response = await fetch(`/api/ws/control`, {
        //         method: 'POST',
        //         headers: {'Content-Type': 'application/json'},
        //         body: JSON.stringify({action: action})
        //     });
        //     const result = await response.json();
        //     console.log("服了啊");
        //     if(!response.ok) {
        //         const errorDetail = result.detail || {};
        //         throw new Error(errorDetail.message || '操作失败');
        //     }
        //     return result;
        // } catch (error) {
        //     console.error('操作失败:', error);
        // }
        if (action === "start")
        {
            console.log("开始");
            const response = await fetch(`/api/startHalfMarathon`);
            const result = await response.json();
            alert(`操作成功: ${JSON.stringify(result)}`);

        }
        else if (action === "stop")
        {
            console.log("停止");
            const response = await fetch(`/api/stopHalfMarathon`);
            const result = await response.json();
            alert(`操作成功: ${JSON.stringify(result)}`);

        }
        else if (action === "reset")
        {
            console.log("重置");
            const response = await fetch(`/api/resetMatch`);
            const result = await response.json();
            alert(`操作成功: ${JSON.stringify(result)}`);

        }
       
    }

    // 状态轮询
    startStatusPolling() {
        this.statusInterval = setInterval(async () => {
            try {
                const response = await fetch('/api/ws/status');
                const status = await response.json();
                //console.log(status);
                document.getElementById('server-status').textContent = 
                    status.is_connected ? '已连接' : '已断开';
            } catch (error) {
                console.error('状态获取失败:', error);
            }
        }, 3000);
    }

    async updatePlayerList() {
        try{
            const response = await fetch('api/playerlist');
            const datas = await response.json();
            const content = document.getElementById('players-list');
            content.innerHTML = '';
            for (const [idpassdata, name, id, type, time, timestamp] of datas){
                const contentEntry = document.createElement('div');
                contentEntry.className = 'pass-data-entry';
                contentEntry.innerHTML = `
                    <span>${id}</span>
                    <span>${time}</span>
                `;
                content.appendChild(contentEntry);
            }
        }
        catch (error) {
            console.error('列表更新失败:', error);
            this.showErrorMessage(`数据加载失败: ${error.message}`);
        }
    }



    async fetchInitialData() {
        const params = new URLSearchParams({
            page: 1,
            page_size: 50,
            sort_by: 'start_number'
        });

        try {
            const response = await fetch(`/admin/players?${params.toString()}`);
            if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);
            const data = await response.json();
            this.renderTable(data);
        } catch (error) {
            console.error('获取数据失败:', error);
            this.showErrorMessage('数据加载失败，请稍后刷新页面');
        }
    }

    showErrorMessage(message) {
        const errorBox = document.createElement('div');
        errorBox.className = 'error-message';
        errorBox.innerHTML = `
            <span class="error-icon">⚠</span>
            ${message}
            <button class="close-btn">&times;</button>
        `;
        
        errorBox.querySelector('.close-btn').onclick = () => {
            errorBox.remove();
        };
        
        document.querySelector('.content-area').prepend(errorBox);
    }

    parseCSV(csvText, kmType) {
        const lines = csvText.split('\n').filter(line => line.trim());
        if (!lines.length) throw new Error('CSV文件内容为空');
        
        const headers = lines[0].split(',').map(h => h.trim());
        const requiredFields = {
            '0': ['选手编号', '姓名', '联系方式'],
            '5': ['选手编号', '5km时间', '心率'],
            '42': ['选手编号', '全程时间', '配速']
        }[kmType];
        
        if (!requiredFields.every(f => headers.includes(f))) {
            throw new Error(`CSV缺少必要字段: ${requiredFields.join(', ')}`);
        }
        
        return lines.slice(1).map(line => {
            const values = line.split(',');
            return {
                kmType: parseInt(kmType),
                data: headers.reduce((obj, key, index) => {
                    obj[key] = values[index]?.trim() || '';
                    return obj;
                }, {})
            };
        });
    }

    async uploadCSVData(csvData) {
        try {
            const response = await fetch('/api/upload-csv', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ records: csvData })
            });
            
            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || '上传失败');
            }
            
            alert('数据成功上传至服务器');
            this.updatePlayerList();
        } catch (error) {
            console.error('上传失败:', error);
            alert(`上传失败: ${error.message}`);
        }
    }

    handleRealTimeData(data) {
        const container = document.getElementById('real-time-data');
        if (container.children.length > 10) {
            container.lastElementChild.remove();
        }
        const entry = document.createElement('div');
        entry.className = 'data-entry';
        entry.innerHTML = `
            <span>${new Date().toLocaleTimeString()}</span>
            <span>${data.type}</span>
            <pre>${JSON.stringify(data.payload, null, 2)}</pre>
        `;
        container.prepend(entry);
    }


    initEventListeners() {
        // 控制按钮点击事件
        document.querySelector('.control-buttons').addEventListener('click', (e) => {
            if (e.target.tagName === 'BUTTON') {
                const action = e.target.dataset.action;
                this.controlConnection(action);
            }
        });

        // 统一导航点击事件处理
        document.querySelectorAll('.nav-link').forEach(link => {
            console.log('添加导航点击事件');
            link.addEventListener('click', (e) => this.handleNavClick(e));
        });

        // 浏览器历史记录事件
        window.addEventListener('popstate', () => {
            this.loadContent(window.location.pathname);
        });

        // const btncontainer = document.getElementById('control-buttons');
        // btncontainer.querySelector('.start-btn')?.addEventListener('click', async () => {
        // const response = await fetch('/api/startHalfMarathon');
        // });
        // btncontainer.querySelector('.stop-btn')?.addEventListener('click', async () => {
        // const response = await fetch('/api/stopHalfMarathon');
        // });
        // btncontainer.querySelector('.resetmatch-btn')?.addEventListener('click', async () => {
        // const response = await fetch('/api/resetMatch');
        // });
    }

    // 新增导航点击处理函数
    handleNavClick(e) {
        console.log('处理导航点击事件，目标URL:', e.target.href);
        e.preventDefault();
        const url = e.target.getAttribute('href');
        history.pushState(null, null, url);
        console.log('开始加载内容:', url);
        this.loadContent(url);
        document.querySelectorAll('.nav-link').forEach(l => 
            l.parentElement.classList.remove('active'));
        e.target.parentElement.classList.add('active');
    }

    // 优化后的动态内容加载
    async loadContent(url, targetId = 'content') {
        try {
            // console.log('正在请求:', url);
            // const response = await fetch(url);
            // console.log('响应状态:', response.status, response.statusText);
            
            // const html = await response.text();
            // console.log('获取到内容，长度:', html.length);
            
            const container = document.getElementById(targetId);
            //container.innerHTML = html;
            console.log('内容注入完成');
            
            this.executeDynamicScripts(container);
            
            // 路由配置加载
            const routes = {
                '/monitor': {
                    component: MonitorComponent,
                    init: (component) => component.renderData({}) // 初始数据可以为空，因为我们不需要任何数据
                },
                '/players': {
                    component: PlayerListComponent,
                    init: (component) => component.renderData()
                },
                '/passdata': {
                    component: PassDataComponent,
                    init: (component) => {
                        component.renderData();
                    }
                }
            };

            // 执行路由匹配
            Object.entries(routes).forEach(([path, config]) => {
                if (url.includes(path)) {
                    if (config.component) {
                        const component = new config.component();
                        config.init(component);
                    } else {
                        config.init();
                    }
                }
            });
        } catch (error) {
            console.error('内容加载失败:', error);
        }
    }

    // 安全的脚本执行方法
    executeDynamicScripts(container) {
        const scripts = container.getElementsByTagName('script');
        Array.from(scripts).forEach(script => {
            const newScript = document.createElement('script');
            if (script.src) {
                newScript.src = script.src;
            } else {
                newScript.text = script.innerHTML;
            }
            document.body.appendChild(newScript).parentNode.removeChild(newScript);
        });
    }

    // 删除重复的renderPlayersTable方法
    renderTable(data, tableId = 'data-table') {
        const tableBody = document.querySelector(`#${tableId} tbody`);
        tableBody.innerHTML = data.map(item => 
            `<tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.ref}</td>
                <td>${item.country || ''}</td>
            </tr>`
        ).join('');
    }
}

// 初始化仪表盘
window.addEventListener('DOMContentLoaded', () => {
  window.AdminDashboard = AdminDashboard;
  window.adminDashboard = new AdminDashboard();
});
})();